package com.fangcun.service.api.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fangcun.bean.api.user.response.UserWalletResponse;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.exception.ProException;
import com.fangcun.common.exception.ProValiDataException;
import com.fangcun.common.util.PublicMethod;
import com.fangcun.common.util.encryption.AESUtils;
import com.fangcun.entity.UserVirtualWallet;
import com.fangcun.mapper.UserTransactionFlowMapper;
import com.fangcun.mapper.UserVirtualWalletMapper;
import com.fangcun.service.api.UserVirtualWalletService;
@Service
public class UserVirtualWalletServiceImpl implements UserVirtualWalletService{
	
	@Autowired
	private UserVirtualWalletMapper userVirtualWalletMapper;
	@Autowired
	private UserTransactionFlowMapper userTransactionFlowMapper;
	
	
	/** 钱包 **/
	@Override
	public UserVirtualWallet wallet(Long userId) throws ProException {
		UserVirtualWallet wallet = userVirtualWalletMapper.selectByUserId(userId);
		if(wallet == null) {
			wallet= new UserVirtualWallet();
			wallet.setUserId(userId);
			wallet.setSign(PublicMethod.getMd5(wallet.getUserId()+"0.000.00",1, true));
			if(userVirtualWalletMapper.insertSelective(wallet) <= 0) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(),"创建钱包错误");
			}
		}else {
			//拿到流水 总增加金额 不用判断
			UserWalletResponse wall=userTransactionFlowMapper.totalRevenue(userId);
			wallet.setBanlanceMoney(wall.getTotalRevenue().subtract(wall.getExpenditure()));
			//重新加密
			wallet.setSign(PublicMethod.getMd5(wallet.getUserId()+""+wallet.getBanlanceMoney()+""+wallet.getFrozenMoney(), 1, true));
			if(userVirtualWalletMapper.updateByPrimaryKeySelective(wallet) <= 0) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(),"流水今天修改到钱包里出错");
			}
			if(!wallet.getSign().equals(PublicMethod.getMd5(wallet.getUserId()+""+wallet.getBanlanceMoney()+""+wallet.getFrozenMoney(), 1, true))) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(),"验证不通过，请联系管理员");
			}
		}
		return wallet;
	}
	
	@Override
	public void update(UserVirtualWallet request) throws ProException {
		//进来Paypwd 是md5   在加密 AES 然后再加md5
		if(request.getPaypwd() != null) {
			try {
				request.setIsPaypwd(1);
				String AESPaypwd = AESUtils.encrypt(request.getPaypwd(),"SHUYINGKEJI12345");
				request.setPaypwd(PublicMethod.getMd5(AESPaypwd, 1, true));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(userVirtualWalletMapper.updateByPrimaryKeySelective(request) <= 0){
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
	}
}
